<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="社区" prop="communityId">
        <el-select
            v-model="queryParams.communityId"
            placeholder="请选择社区"
            clearable
            filterable
        >
          <el-option
              v-for="ops in optiones"
              :key="ops.communityId"
              :label="ops.name"
              :value="ops.communityId"
          />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">

      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['property:work:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['property:work:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 修改表格，将操作列固定 -->
    <el-table v-loading="loading" :data="workList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" fixed="left" />
      <el-table-column label="工单ID" align="center" prop="workOrderId" width="80" />
      <el-table-column label="社区" align="center" prop="name" width="120" />
      <el-table-column label="工单类型" align="center" prop="workOrderType" width="120" />
      <el-table-column label="工单标题" align="center" prop="title" width="150" show-overflow-tooltip />
      <el-table-column label="工单内容" align="center" prop="content" min-width="200" show-overflow-tooltip />
      <el-table-column label="房屋ID" align="center" prop="houseId" width="100" />
      <el-table-column label="报告人" align="center" prop="reporter" width="120" />
      <el-table-column label="报告人电话" align="center" prop="reporterPhone" width="130" />
      <el-table-column label="报告时间" align="center" prop="reportTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.reportTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="处理人" align="center" prop="assignee" width="120" />
      <el-table-column label="分配时间" align="center" prop="assignTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.assignTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status" width="120" />
      <el-table-column label="优先级" align="center" prop="priority" width="100" />
      <el-table-column label="处理描述" align="center" prop="handleDescription" min-width="200" show-overflow-tooltip />
      <el-table-column label="处理时间" align="center" prop="handleTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.handleTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>

      <!-- 修改后的图片列 -->
      <el-table-column label="图片" align="center" width="150">
        <template #default="scope">
          <div class="image-cell">
            <template v-if="scope.row.images">
              <!-- 单张图片展示 -->
              <el-image
                  v-if="typeof scope.row.images === 'string'"
                  class="table-image"
                  :src="scope.row.images"
                  :preview-src-list="[scope.row.images]"
                  fit="contain"
                  hide-on-click-modal
                  preview-teleported
              />
              <!-- 多张图片展示 -->
              <el-carousel
                  v-else-if="Array.isArray(scope.row.images) && scope.row.images.length > 0"
                  indicator-position="outside"
                  height="100px"
                  :autoplay="false"
              >
                <el-carousel-item v-for="(img, index) in scope.row.images" :key="index">
                  <el-image
                      class="table-image"
                      :src="img"
                      :preview-src-list="scope.row.images"
                      fit="contain"
                      hide-on-click-modal
                      preview-teleported
                  />
                </el-carousel-item>
              </el-carousel>
            </template>
            <span v-else class="no-image">无图片</span>
          </div>
        </template>
      </el-table-column>


      <el-table-column label="预计完成时间" align="center" prop="estimatedTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.estimatedTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="实际完成时间" align="center" prop="actualTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.actualTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>

      <!-- 固定操作列在右侧 -->
      <el-table-column
          label="操作"
          align="center"
          class-name="small-padding fixed-width"
          fixed="right"
          width="150">
        <template #default="scope">
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['property:work:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

  </div>
</template>

<script setup name="Work">
import { listWork, getWork, delWork, addWork, updateWork } from "@/api/property/work"
import {getoption} from "@/api/property/repair"
import {ElMessage} from "element-plus";
import {ref} from "vue";
import {getToken} from "@/utils/auth.js";
const { proxy } = getCurrentInstance()

const workList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const optiones = ref([])
const headers = ref({Authorization: "Bearer " + getToken()})

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    communityId: null,
    name: null,
    workOrderType: null,
    title: null,
    content: null,
    houseId: null,
    reporter: null,
    reporterPhone: null,
    reportTime: null,
    assignee: null,
    assignTime: null,
    status: null,
    priority: null,
    handleDescription: null,
    handleTime: null,
    images: null,
    estimatedTime: null,
    actualTime: null,
  },
  rules: {
  }
})

const { queryParams, form, rules } = toRefs(data)

const fetchOptions = async () => {
  try {
    const response = await getoption()
    optiones.value = response.data || response
  } catch (error) {
    console.log("获取数据失败:", error)
  }
}
/** 查询内部工单列表 */
function getList() {
  loading.value = true
  listWork(queryParams.value).then(response => {
    workList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    workOrderId: null,
    communityId: null,
    name: null,
    workOrderType: null,
    title: null,
    content: null,
    houseId: null,
    reporter: null,
    reporterPhone: null,
    reportTime: null,
    assignee: null,
    assignTime: null,
    status: null,
    priority: null,
    handleDescription: null,
    handleTime: null,
    images: null,
    estimatedTime: null,
    actualTime: null,
    createTime: null,
    updateTime: null
  }
  proxy.resetForm("workRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.workOrderId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加内部工单"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _workOrderId = row.workOrderId || ids.value
  getWork(_workOrderId).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改内部工单"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["workRef"].validate(valid => {
    if (valid) {
      if (form.value.workOrderId != null) {
        updateWork(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addWork(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _workOrderIds = row.workOrderId || ids.value
  proxy.$modal.confirm('是否确认删除内部工单编号为"' + _workOrderIds + '"的数据项？').then(function() {
    return delWork(_workOrderIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

//图片上传
const handleAvatarSuccess = (response) => {
  ElMessage.success("上传成功")
  form.value.images = response
}

const beforeAvatarUpload = (rawFile) => {
  if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/jpg' && rawFile.type !== 'image/png') {
    ElMessage.error('上传的图片或格式不正确')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('上传的照片不超过2MB!')
    return false
  }
  return true
}





/** 导出按钮操作 */
function handleExport() {
  proxy.download('property/work/export', {
    ...queryParams.value
  }, `work_${new Date().getTime()}.xlsx`)
}
// 在组件挂载时调用
onMounted(() => {
  fetchOptions()
})
getList()
</script>
